package GUI;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Toolkit;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSplitPane;

import java.awt.FlowLayout;

import javax.swing.JLabel;

import java.awt.Color;
import java.awt.GridBagLayout;

import javax.swing.JTextField;

import java.awt.GridBagConstraints;

import javax.swing.BoxLayout;

import java.awt.GridLayout;

import net.miginfocom.swing.MigLayout;

import javax.swing.JPasswordField;
import javax.swing.JButton;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import objects.Author;
import objects.Chair;
import objects.Reviewer;
import objects.SubChair;
import objects.User;
import dbAccess.authorAccess;
import dbAccess.chairAccess;
import dbAccess.confAccess;
import dbAccess.reviewerAccess;
import dbAccess.subChairAccess;
import dbAccess.userAccess;

import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

/**
 * Login page to the Conference. 
 * Needs first name and last name.
 * If not registered then there is an
 * option to register. 
 * 
 * @author Crystal Miraflor
 *
 */
public class Login extends JFrame {
	
	/** A long integer ID number, in case this class should be serialized. */
	private static final long serialVersionUID = -559172165987711682L;
	
	/** The base JPanel (generated by WindowBuilder) for this GUI. */
	private JPanel contentPane;
	
	/** The inner JPanel (generated by WindowBuilder) for this GUI. */
	private final JPanel panel = new JPanel();

	/** Labels to indicate what the user should input in the fields. */
	private final JLabel lblUsername = new JLabel("Username");
	private final JLabel lblPassword = new JLabel("Password");
	
	/** A textfield for the username. */
	private final JTextField textField = new JTextField();
	
	/** A passwordfield for the password, so that the password input is hidden. */
	private final JPasswordField passwordField = new JPasswordField();
	
	/** The button for login. */
	private final JButton btnLogin = new JButton("Login");
	
	/** The Welcome message. */
	private final JLabel lblWelcome = new JLabel("Welcome!");
	
	/** A blank label generated and used by WindowBuilder. */
	private final JLabel label = new JLabel("");
	
	/** A drop-down list of the different conferences. */
	private final JComboBox<String> comboBox = new JComboBox<String>();
	
    /** The first conference ID associated with the user who is logging in. */
    public int my_conf_id;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Login frame = new Login();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * @throws IOException 
	 */
	public Login() throws IOException {
		setTitle("Conference Manager - TeamAwesome360");
		textField.setColumns(10);

		initGUI();
	}
	
	private void initGUI() throws IOException {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 440, 290);
		setResizable(false);
		contentPane = new JPanel();
		contentPane.setBackground(Color.GRAY);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		panel.setBackground(Color.GRAY);
		panel.setForeground(Color.WHITE);
		lblWelcome.setFont(new Font("Vijaya", Font.BOLD, 18));
		lblWelcome.setForeground(Color.WHITE);
		lblUsername.setForeground(Color.WHITE);
		lblPassword.setForeground(Color.WHITE);
		btnLogin.setSelected(false);
		//btnLogin.setMnemonic(KeyEvent.VK_ENTER);
//		String path = "Image1.jpg";
//        File file = new File("robotech-pattern-chris-alvarez-deviantart_109855.jpg");
//        BufferedImage image = ImageIO.read(file);
//        label.setIcon(new ImageIcon(image));
		label.setBackground(new Color(0, 128, 128));
		label.setOpaque(true);
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addComponent(panel, GroupLayout.PREFERRED_SIZE, 444, GroupLayout.PREFERRED_SIZE)
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addComponent(panel, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE)
		);
		comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"OOPSLA", "LAS", "IMCEE"}));
		GroupLayout gl_panel = new GroupLayout(panel);
		setUpOverallLayout(gl_panel);
		panel.setLayout(gl_panel);
		contentPane.setLayout(gl_contentPane);
		
		
		btnLogin.addActionListener(new ActionListener() {

			/**
			 * Handles actions of the Login button, creating a new UserGUI panel based on
			 * the user's role, detected from the input.
			 * 
			 * @author Margaret 
			 */
			@Override
			public void actionPerformed(ActionEvent arg0) {
				User me = null;//removed the blank constructor of user, so users need valid fields ~Brian
				userAccess db_access = new userAccess();
				if (!db_access.checkUser(textField.getText(), passwordField.getText())) {
					int registration = JOptionPane.showConfirmDialog(null, "Looks like you're not a member yet.  Want to register?", 
							"New User", JOptionPane.YES_NO_OPTION);
					if (registration == JOptionPane.YES_OPTION) {
						String new_name = JOptionPane.showInputDialog(null, "Please tell us who you are.  Type your name: FIRST LAST", null);
						String[] names = new_name.split("\\s+");
						System.out.println(names);
						User newbie = new User(names[0], names[1], textField.getText(), passwordField.getText());
						db_access = new userAccess();
						db_access.addUser(newbie);
						
						getContentPane().remove(panel);
						db_access = new userAccess();
						
						me = db_access.getUser(textField.getText());
						contentPane = new UserGUI(me);
						setContentPane(contentPane);
						setTitle("User Page");//set window title
						pack();
					}
				} else {
					getContentPane().remove(panel);
					db_access = new userAccess();
					me = db_access.getUser(textField.getText());
					contentPane = new UserGUI(me, returnConfID());
					setContentPane(contentPane);
					setTitle("User Page");//set window title
					pack();
				}
				comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"OOPSLA", "ICMEE", "PNWCSE", "LAS"}));
				comboBox.setBounds(212, 51, 205, 20);
				comboBox.setLayout(new BorderLayout());
				panel.add(comboBox);
				comboBox.setVisible(true);
				
				// Identifying conference id and user role
				confAccess conf_access = new confAccess();
				int conf_id = conf_access.getConf(comboBox.getSelectedItem().toString()); // user's conference	

				db_access = new userAccess();
				String role = db_access.getUserRole(textField.getText(), comboBox.getSelectedItem().toString());
				
				// Make default role 'Author'
				if (role==null) {
					db_access = new userAccess();
					db_access.addUserRole(textField.getText(), conf_id, "AUTHORS");
				}
				
				db_access = new userAccess();
				me = db_access.getUser(textField.getText()); // returns User based on inputed username
				getContentPane().remove(panel);
				
				if (role.equals("CHAIRS")) {
					chairAccess chairs = new chairAccess();
					me = chairs.getChair(me.getName());
					setTitle("Program Chair");//set window title
				} else if (role.equals("SUBCHAIRS")) {	
					subChairAccess subs = new subChairAccess();
					me = subs.getSubChair(me.getFirstname() + " " + me.getLastname()); // OK
					setTitle("SubProgram Chair");//set window title
				} else if (role.equals("REVIEWERS")) {
					reviewerAccess reviewers = new reviewerAccess();
					me = reviewers.getReviewer(me.getFirstname() + " " + me.getLastname()); // OK
					setTitle("Reviewer");//set window title
				} else if (role.equals("AUTHORS")) {
					authorAccess authors = new authorAccess();
					me = authors.getAuthor(me.getFirstname());
					setTitle("Author");//set window title
				}
				contentPane = new UserGUI(me, conf_id);
				setContentPane(contentPane);
				pack();
			}
		});
	}
	
	public int returnConfID()
	{
	    confAccess conf_access = new confAccess();
        my_conf_id = conf_access.getConf(comboBox.getSelectedItem().toString());
	    return my_conf_id;
	}
	
	/**
	 * Sets the GroupLayout specifications for the given GroupLayout panel
	 * and adds to it the components which are fields in this Login.java class.
	 * This panel indicates the overall visual layout of the Login.java GUI.
	 * 
	 * @author WindowBuilder, method created by Margaret
	 * @param gl_panel the given GroupLayout panel
	 */
	private void setUpOverallLayout(GroupLayout gl_panel) {
		gl_panel.setHorizontalGroup(
				gl_panel.createParallelGroup(Alignment.LEADING)
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(212)
						.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 205, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(285)
						.addComponent(lblWelcome))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(138)
						.addComponent(lblUsername, GroupLayout.PREFERRED_SIZE, 64, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(138)
						.addComponent(lblPassword, GroupLayout.PREFERRED_SIZE, 64, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(212)
						.addComponent(textField, GroupLayout.PREFERRED_SIZE, 205, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(212)
						.addComponent(passwordField, GroupLayout.PREFERRED_SIZE, 205, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(285)
						.addComponent(btnLogin, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE))
					.addComponent(label, GroupLayout.PREFERRED_SIZE, 434, GroupLayout.PREFERRED_SIZE)
			);
			gl_panel.setVerticalGroup(
				gl_panel.createParallelGroup(Alignment.LEADING)
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(90)
						.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addGap(41)
						.addComponent(lblWelcome)
						.addGap(7)
						.addComponent(lblUsername)
						.addGap(10)
						.addComponent(lblPassword))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(174)
						.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(198)
						.addComponent(passwordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createSequentialGroup()
						.addGap(228)
						.addComponent(btnLogin))
					.addComponent(label, GroupLayout.PREFERRED_SIZE, 262, GroupLayout.PREFERRED_SIZE)
			);
	}
}
